<template>  
  <div>  
    <div class="fulltable"> <!-- 外层容器 -->  
      <div class="full thisfull"> <!-- 主容器 -->  
        <div class="box box1" >  
          <div class="search">  
            <el-input  
              v-model="searchName"  
              placeholder="输入名称"  
              @input="filterData"  
              clearable  
              style="margin-bottom: 10px;width: 200px;">  
            </el-input>  
            <span style="margin-left: 10px;width: 200px;">部门管理员只能查看本部门数据</span>
          </div>  
          <div class="table-wrapper">  
              <el-table  
                  :data="filteredWorkTimeData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"  
                  border  
                  style="width: 100%">  
                  <el-table-column prop="name" width="180" label="名称" fixed></el-table-column>  
                  <el-table-column prop="workTime"  label="工作时间" fixed></el-table-column>  
              </el-table>  
              </div>  

              <el-pagination  
              @size-change="handleSizeChange"  
              @current-change="handleCurrentChange"  
              :current-page="currentPage"  
              :page-sizes="[5, 10, 20]"  
              :page-size="pageSize"  
              layout="total, sizes, prev, pager, next, jumper"  
              :total="filteredWorkTimeData.length"  
              style="margin-left: 170px;"  
              ></el-pagination>  
        </div> <!-- Box 1 -->  

        <div class="box box2" >  
          <div class="search">  
            <el-input  
              v-model="searchTaskName"  
              placeholder="输入名称"  
              @input="filterTaskData"  
              clearable  
              style="margin-bottom: 10px;width: 200px;">  
            </el-input>  
            <span style="margin-left: 10px;width: 200px;">部门管理员只能查看本部门数据</span>
          </div>  
          <div class="table-wrapper">  
            <el-table  
                :data="filteredTaskRateData.slice((taskCurrentPage - 1) * taskPageSize, taskCurrentPage * taskPageSize)"  
                border  
                style="width: 100%">  
                <el-table-column prop="name" width="180" label="名称" fixed></el-table-column>  
                <el-table-column prop="rate" label="任务完成率" fixed></el-table-column>  
            </el-table>  
            </div>  

            <el-pagination  
              @size-change="handleTaskSizeChange"  
              @current-change="handleTaskCurrentChange"  
              :current-page="taskCurrentPage"  
              :page-sizes="[5, 10, 20]"  
              :page-size="taskPageSize"  
              layout="total, sizes, prev, pager, next, jumper"  
              :total="filteredTaskRateData.length"  
              style="margin-left: 170px;"  
            ></el-pagination>  
        </div> <!-- Box 2 -->  

        <div class="box box3" >  
          <div class="search">  
            <el-input  
              v-model="searchPerformanceName"  
              placeholder="输入名称"  
              @input="filterPerformanceData"  
              clearable  
              style="margin-bottom: 10px;width: 200px;">  
            </el-input>  
            <span style="margin-left: 10px;width: 200px;">部门管理员只能查看本部门数据</span>
          </div>  
          <div class="table-wrapper">  
            <el-table  
                :data="filteredPerformanceData.slice((performanceCurrentPage - 1) * performancePageSize, performanceCurrentPage * performancePageSize)"  
                border  
                style="width: 100%">  
                <el-table-column prop="name" width="180" label="名称" fixed></el-table-column>  
                <el-table-column prop="deptName" width="180" label="部门" fixed></el-table-column>  
                <el-table-column prop="score" label="绩效" fixed></el-table-column>  
            </el-table>  
            </div>  

            <el-pagination  
              @size-change="handlePerformanceSizeChange"  
              @current-change="handlePerformanceCurrentChange"  
              :current-page="performanceCurrentPage"  
              :page-sizes="[5, 10, 20]"  
              :page-size="performancePageSize"  
              layout="total, sizes, prev, pager, next, jumper"  
              :total="filteredPerformanceData.length"  
              style="margin-left: 170px;"  
            ></el-pagination>  
        </div> <!-- Box 3 -->  

        <div class="box box4" >
          
      <div class="chart-selector">
        <el-select v-model="chartType" @change="updateChart" placeholder="选择图表类型">
          <el-option label="饼状图" value="pie"></el-option>
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="折线图" value="line"></el-option>
        </el-select>
        <span style="margin-left: 10px;width: 200px;">始终展示所有部门数据</span>
      </div>
      <div ref="chart" class="chart" style="height: 300px;"></div>
    </div><!-- Box 4 -->  
      </div>  
    </div>  
  </div>  
</template>  

<script>  
import { getWorkTime, getTaskRate, getPerformance,getUseSituation } from '@/api/report';  
import * as echarts from 'echarts';
export default {  
data() {  
  return {  
    workTimeData: [],  
    taskRateData: [], // 新增任务完成率数据  
    performanceData: [], // 新增绩效数据  
    currentPage: 1,  
    pageSize: 5,  
    searchName: '',  
    taskCurrentPage: 1, // 新增任务页码  
    taskPageSize: 5, // 新增任务每页显示数量  
    searchTaskName: '', // 新增任务过滤条件  
    performanceCurrentPage: 1, // 新增绩效页码  
    performancePageSize: 5, // 新增绩效每页显示数量  
    searchPerformanceName: '', // 新增绩效名称过滤条件  
    selectedDept: '', // 新增部门选择  
    minScore: null, // 最小绩效  
    maxScore: null, // 最大绩效  
    departments: [], // 存储部门列表  
    chartType: 'pie', // 默认图表类型
    chartData: [], // 存储获取的图表数据
  };  
},  
mounted() {  
  this.getWorkTime();  
  this.getTaskRate(); // 获取任务完成率数据  
  this.getPerformanceList(); // 获取绩效数据  
  this.getDepartments(); // 获取部门列表  
  this.getUseSituationData(); // 获取使用情况数据
},  
computed: {  
  filteredWorkTimeData() {  
    return this.workTimeData.filter(item => {  
      return item.name.toLowerCase().includes(this.searchName.toLowerCase());  
    });  
  },  
  filteredTaskRateData() { // 新增计算属性：过滤任务完成率数据  
    return this.taskRateData.filter(item => {  
      return item.name.toLowerCase().includes(this.searchTaskName.toLowerCase());  
    });  
  },  
  filteredPerformanceData() { // 新增计算属性：过滤绩效数据  
    return this.performanceData.filter(item => {  
      const matchesName = item.name.toLowerCase().includes(this.searchPerformanceName.toLowerCase());
      const matchesDept = this.selectedDept ? item.deptId === this.selectedDept : true;
      const matchesScore = (this.minScore !== null ? item.score >= this.minScore : true) && (this.maxScore !== null ? item.score <= this.maxScore : true);
      return matchesName && matchesDept && matchesScore;
    });  
  },  
},  
methods: {  
  getUseSituationData() {
      getUseSituation()
        .then(res => {
          this.chartData = res.data; // 假设返回的数据格式为 [{ name: '模块1', count: 10 }, ...]
          this.renderChart();
        })
        .catch(err => {
          console.error(err);
          this.$message.error('获取模块使用次数失败');
        });
    },
    renderChart() {
      const chart = echarts.init(this.$refs.chart);
      const option = this.getChartOption();
      chart.setOption(option);
    },getChartOption() {  
    const names = this.chartData.map(item => item.name);  
    const counts = this.chartData.map(item => item.count);  
    
    if (this.chartType === 'pie') {  
        return {  
            title: {   
                text: '模块使用情况',   
                left: 'center',  
                textStyle: {  
                    fontSize: 16,  
                    fontWeight: 'bold'  
                }  
            },  
            tooltip: {  
                trigger: 'item',  
                formatter: '{a} <br/>{b}: {c} ({d}%)'  
            },  
            legend: {  
                orient: 'vertical',  
                left: 'left',  
                data: names  
            },  
            series: [{  
                name: '使用次数',  
                type: 'pie',  
                radius: ['40%', '70%'],  
                avoidLabelOverlap: false,  
                itemStyle: {  
                    borderRadius: 10,  
                    borderColor: '#fff',  
                    borderWidth: 2  
                },  
                left:"35%",
                label: {  
                    show: true,  
                    formatter: '{b}: {c} ({d}%)'  
                },  
                emphasis: {  
                    label: {  
                        show: true,  
                        fontSize: '18',  
                        fontWeight: 'bold'  
                    }  
                },  
                data: this.chartData.map(item => ({  
                    value: item.count,  
                    name: item.name  
                }))  
            }],  
            // 隐藏横纵坐标  
            xAxis: {  
                show: false  
            },  
            yAxis: {  
                show: false  
            }  
        };  
    } else if (this.chartType === 'bar') {  
        return {  
            title: {   
                text: '模块使用情况',   
                left: 'center',  
                textStyle: {  
                    fontSize: 16,  
                    fontWeight: 'bold'  
                }  
            },  
            tooltip: {  
                trigger: 'axis',  
                axisPointer: {  
                    type: 'shadow'  
                },  
                formatter: function(params) {  
                    const total = counts.reduce((a, b) => a + b, 0);  
                    const percent = ((params[0].value / total) * 100).toFixed(2);  
                    return `${params[0].name}<br/>使用次数: ${params[0].value}<br/>占比: ${percent}%`;  
                }  
            },  
            grid: {  
                left: '3%',  
                right: '4%',  
                bottom: '3%',  
                containLabel: true  
            },  
            xAxis: {  
              show:true,
                type: 'category',  
                data: names,  
                axisLabel: {  
                    interval: 0,  
                    rotate: 30,  
                    textStyle: {  
                        fontSize: 12  
                    }  
                },  
                axisLine: {  
                    show: true  
                },  
                axisTick: {  
                    show: true  
                }  
            },  
            yAxis: {  
              show:true,
                type: 'value',  
                name: '使用次数',  
                axisLine: {  
                    show: true  
                },  
                axisTick: {  
                    show: true  
                },  
                splitLine: {  
                    show: true  
                }  
            },  
            series: [{  
                type: 'bar',  
                data: counts,  
                barWidth: '40%',  
                itemStyle: {  
                    color: '#409EFF'  
                },  
                label: {  
                    show: true,  
                    position: 'top',  
                    formatter: function(params) {  
                        const total = counts.reduce((a, b) => a + b, 0);  
                        const percent = ((params.value / total) * 100).toFixed(2);  
                        return `${params.value}`;  
                    }  
                }  
            }]  
        };  
    } else if (this.chartType === 'line') {  
        return {  
            title: {   
                text: '模块使用情况',   
                left: 'center',  
                textStyle: {  
                    fontSize: 16,  
                    fontWeight: 'bold'  
                }  
            },  
            tooltip: {  
                trigger: 'axis',  
                formatter: function(params) {  
                    const total = counts.reduce((a, b) => a + b, 0);  
                    const percent = ((params[0].value / total) * 100).toFixed(2);  
                    return `${params[0].name}<br/>使用次数: ${params[0].value}<br/>占比: ${percent}%`;  
                }  
            },  
            grid: {  
                left: '3%',  
                right: '4%',  
                bottom: '3%',  
                containLabel: true  
            },  
            xAxis: {  
              show:true,
                type: 'category',  
                data: names,  
                axisLabel: {  
                    interval: 0,  
                    rotate: 30,  
                    textStyle: {  
                        fontSize: 12  
                    }  
                },  
                axisLine: {  
                    show: true  
                },  
                axisTick: {  
                    show: true  
                }  
            },  
            yAxis: {  
              show:true,
                type: 'value',  
                name: '使用次数',  
                axisLine: {  
                    show: true  
                },  
                axisTick: {  
                    show: true  
                },  
                splitLine: {  
                    show: true  
                }  
            },  
            series: [{  
                type: 'line',  
                data: counts,  
                symbol: 'circle',  
                symbolSize: 8,  
                itemStyle: {  
                    color: '#409EFF'  
                },  
                label: {  
                    show: true,  
                    position: 'top',  
                    formatter: '{c}'  
                },  
                lineStyle: {  
                    width: 3,  
                    color: '#409EFF'  
                }  
            }]  
        };  
    }  
},  
    updateChart() {
      this.renderChart(); // 更新图表
    },
  getWorkTime() {  
    getWorkTime()  
      .then(res => {  
        this.workTimeData = res.data;  
      })  
      .catch(err => {  
        console.log(err);  
        this.$message.error('获取工作时间列表失败');  
      });  
  },  

  getTaskRate() {  
    getTaskRate()  
      .then(res => {  
        this.taskRateData = res.data; // 保存任务完成率数据  
      })  
      .catch(err => {  
        console.log(err);  
        this.$message.error('获取任务完成率数据失败');  
      });  
  },  

  getPerformanceList() {  
    getPerformance()  
      .then(res => {  
        console.log(res.data);
        this.performanceData = res.data; // 保存绩效数据  
      })  
      .catch(err => {  
        console.log(err);  
        this.$message.error('获取绩效数据失败');  
      });  
  },  

  getDepartments() {  
    // Assuming you have an API to get departments
    // This is a placeholder for the actual implementation
    this.departments = [
      { id: 1, deptName: '部门A' },
      { id: 2, deptName: '部门B' },
      { id: 3, deptName: '部门C' },
    ];
  },

  handleSizeChange(val) {  
    this.pageSize = val;  
    this.currentPage = 1; // Reset to first page on page size change  
  },  
  handleCurrentChange(val) {  
    this.currentPage = val;  
  },  
  filterData() {  
    this.currentPage = 1; // Reset to first page on filter change  
  },  
  
  handleTaskSizeChange(val) { // 新增：处理任务表格尺寸变更  
    this.taskPageSize = val;  
    this.taskCurrentPage = 1; // Reset to first page on page size change  
  },  
  handleTaskCurrentChange(val) { // 新增：处理当前任务页码变更  
    this.taskCurrentPage = val;  
  },  
  filterTaskData() { // 新增：处理任务过滤  
    this.taskCurrentPage = 1; // Reset to first page on filter change  
  },  

  handlePerformanceSizeChange(val) { // 新增：处理绩效表格尺寸变更  
    this.performancePageSize = val;  
    this.performanceCurrentPage = 1; // Reset to first page on page size change  
  },  
  handlePerformanceCurrentChange(val) { // 新增：处理当前绩效页码变更  
    this.performanceCurrentPage = val;  
  },  
  filterPerformanceData() { // 新增：处理绩效过滤  
    this.performanceCurrentPage = 1; // Reset to first page on filter change  
  },  
},  
};  
</script>  

<style>  
.fulltable {  
  margin-top: 20px;  
  height: 700px;  
}  

.full {  
  height: 800px;  
  margin: 0;  
  padding: 0;  
  background: pink;  
  padding-top: 10px;  
  margin-left: 20px;  
  margin-right: 20px;  
  border-radius: 10px;  
  flex: 1;  
}  

.thisfull {  
  display: flex; /* 使用 Flexbox 布局 */  
  flex-wrap: wrap; /* 允许换行 */  
  justify-content: space-between; /* 设置盒子之间的间距 */  
}  

.box {  
  width: calc(50% - 10px); /* 每行两个盒子，考虑间距 */  
  height: 385px; /* 根据需求调整高度 */  
  background-color: lightblue; /* 根据需求调整颜色 */  
  border-radius: 15px; /* 圆角 */  
  margin-bottom: 20px; /* 每个盒子下方的间距 */  
}  

.table-wrapper {  
  max-height: 289px; /* 设置表格最大高度 */  
  overflow-y: auto; /* 启用竖向滚动 */  
}  

.el-table th {  
  position: sticky; /* 固定表头 */  
  top: 0; /* 定位于顶部 */  
  background-color: pink; /* 表头背景色，与外部容器相同，避免重叠 */  
  z-index: 1; /* 确保表头在最上层 */  
}  

.el-table td {  
  background-color: white; /* 数据行背景色 */  
}  
</style>  